<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import {
  getSupplierListApi,
  deleteSupplierApi,
  putSupplierUpdateApi,
} from "@/api/Supplier";
import { SupplierListData, SupplierData } from "@/api/Supplier/res";
import { SupplierSearchData, PaginationType } from "@/api/Supplier/param";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/User";

// mockData
let sourceData = ref(["销售订单", "库存备货", "其他"]);
let stateData = ref(["未分解", "已分解", "已完成", "已关闭", "已撤回"]);
let tableData = ref<SupplierData[]>([]);
let total = ref(0);
let showDatePicker = ref(false);
let loading = ref(false);
const userStore = useUserStore();
// 存储当前需要退货的条目
let currentShowData = ref({});
let searchData = ref<SupplierSearchData>({
  returnDate: "",
  returnName: "",
  purchaseName: "",
});
let params = ref<PaginationType>({
  currentPage: 1,
  pageSize: 10,
});
let ifSearch = ref(false);
let returnVisible = ref(false);
const filteredSearchData: Partial<SupplierSearchData> = {};
const $router = useRouter();

const handler = (page) => {
  params.value.currentPage = page;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const sizeHandler = (page_size) => {
  params.value.pageSize = page_size;
  if (ifSearch.value) {
    getTableData(filteredSearchData);
  } else {
    getTableData();
  }
};
const getTableData = async (data?) => {
  try {
    loading.value = true;
    const TotalRes = await getSupplierListApi();
    total.value = TotalRes.results.length;
    const res: SupplierListData = await getSupplierListApi(data, params.value);
    tableData.value = res.results;
    if (ifSearch.value) {
      total.value = res.results.length;
    }
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getTableData();
});

const gotoAdd = () => {
  $router.push("/storage/entrance/addSupplier");
};
const gotoDetail = (objectId) => {
  $router.push({
    path: "/storage/entrance/supplierDetail",
    query: { objectId },
  });
};
const handleClick = (row) => {
  returnVisible.value = true;
  currentShowData.value = row;
};
const editSupplier = (objectId) => {
  $router.push({ path: "/storage/entrance/editSupplier", query: { objectId } });
};
const reset = () => {
  searchData.value = {
    returnDate: "",
    returnName: "",
    purchaseName: "",
  };
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  ifSearch.value = false;
  getTableData();
};
const onSearch = () => {
  let allFieldsEmpty = true;
  Object.keys(filteredSearchData).forEach((key) => {
    delete filteredSearchData[key];
  });
  for (const key in searchData.value) {
    if (searchData.value[key] !== "") {
      allFieldsEmpty = false;
      filteredSearchData[key] = searchData.value[key];
    }
  }
  ifSearch.value = !allFieldsEmpty;
  params.value.currentPage = 1;
  params.value.pageSize = 10;
  getTableData(filteredSearchData);
};
const onCancel = async (objectId: string) => {
  try {
    const res: any = await deleteSupplierApi(objectId);
    ElMessage({ type: "success", message: "删除成功" });
    getTableData();
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  }
};
const confirmReturn = async () => {
  try {
    let data = {
      ...currentShowData.value,
      ifReturn: "已退货",
      updater: userStore.username,
    };
    const updateData = Object.keys(data).reduce((obj, key) => {
      if (key !== "createdAt") {
        obj[key] = data[key];
      }
      return obj;
    }, {} as SupplierData);
    const res: any = await putSupplierUpdateApi(updateData as SupplierData);
    ElMessage({ type: "success", message: "退货成功" });
    returnVisible.value = false;
    getTableData();
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  }
};
const revoke = async (row) => {
  try {
    let data = { ...row, ifReturn: "未退货", updater: userStore.username };
    const updateData = Object.keys(data).reduce((obj, key) => {
      if (key !== "createdAt") {
        obj[key] = data[key];
      }
      return obj;
    }, {} as SupplierData);
    const res: any = await putSupplierUpdateApi(updateData as SupplierData);
    ElMessage({ type: "success", message: "撤回成功" });
    returnVisible.value = false;
    getTableData();
  } catch (err: any) {
    ElMessage({ type: "error", message: err.message });
  }
};
</script>

<template>
  <div style="padding: 20px">
    <el-card>
      <div class="operateContainer">
        <div
          class="formContainer"
          :style="showDatePicker ? 'height:85px' : 'height:32px'"
        >
          <el-form inline :model="searchData">
            <el-form-item prop="returnName">
              <el-input
                placeholder="请输入退货单号/名称"
                style="width: 250px"
                v-model.trim="searchData.returnName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="purchaseName">
              <el-input
                placeholder="请输入采购单号/名称"
                style="width: 250px"
                v-model.trim="searchData.purchaseName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="returnDate">
              <el-date-picker
                style="width: 250px"
                type="date"
                placeholder="请选择退货日期"
                v-model.trim="searchData.returnDate"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div class="searchOperate">
          <div class="button">
            <el-button type="primary" plain style="width: 80px" @click="reset"
              >重置</el-button
            >
            <el-button type="primary" style="width: 80px" @click="onSearch"
              >查询</el-button
            >
          </div>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>
        <span style="font-weight: bold">供应商退货</span>
      </template>
      <div class="operate">
        <el-button style="width: 80px" type="primary" @click="gotoAdd"
          >新增</el-button
        >
        <el-button style="width: 80px" type="primary" plain>导出</el-button>
      </div>
      <el-table
        :data="tableData"
        style="margin-top: 15px"
        border
        v-loading="loading"
      >
        <el-table-column type="selection" align="center"> </el-table-column>
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
          fixed="left"
        ></el-table-column>
        <el-table-column
          align="center"
          label="退货单名称"
          fixed="left"
          prop="returnName"
        >
          <template #="{ row, $index }">
            <el-button link type="primary" @click="gotoDetail(row.objectId)">{{
              row.returnName
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="退货单编号"
          fixed="left"
          prop="returnId"
        ></el-table-column>
        <el-table-column
          align="center"
          label="退货日期"
          prop="returnDate"
        ></el-table-column>
        <el-table-column
          align="center"
          label="采购单名称"
          prop="purchaseName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="采购单号"
          prop="purchaseId"
        ></el-table-column>
        <el-table-column
          align="center"
          label="供应商"
          prop="purchaseName"
        ></el-table-column>
        <el-table-column
          align="center"
          label="退货总数"
          prop="returnNum"
        ></el-table-column>
        <el-table-column
          align="center"
          label="备注"
          width="250"
          prop="remark"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template #="{ row, $index }">
            <el-popconfirm
              v-if="row.ifReturn == '已退货'"
              title="你确定要撤回吗?"
              @confirm="revoke(row)"
            >
              <template #reference>
                <el-button link type="primary">撤回</el-button>
              </template>
            </el-popconfirm>
            <el-button
              link
              type="primary"
              @click="handleClick(row)"
              v-if="row.ifReturn == '未退货'"
            >
              退货
            </el-button>
            <el-button
              v-if="row.ifReturn == '未退货'"
              link
              type="primary"
              @click="editSupplier(row.objectId)"
              >编辑</el-button
            >
            <el-popconfirm
              v-if="row.ifReturn == '未退货'"
              title="你确定要删除吗?"
              @confirm="onCancel(row.objectId)"
            >
              <template #reference>
                <el-button link type="primary">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.currentPage"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="prev,pager,next,jumper,->,sizes,total"
        :total="total"
        @current-change="handler"
        @size-change="sizeHandler"
        style="margin-top: 10px"
      ></el-pagination>
    </el-card>
    <el-dialog v-model="returnVisible" title="提示" width="500">
      <div style="display: flex; align-items: center">
        <el-icon style="margin-right: 10px" size="16" color="#FA8C15"
          ><InfoFilled
        /></el-icon>
        <span>确认执行退货吗？</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="returnVisible = false" style="width: 80px"
            >取消</el-button
          >
          <el-button type="primary" @click="confirmReturn" style="width: 80px">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.operateContainer {
  display: flex;
  align-content: center;
  justify-content: space-between;
  .formContainer {
    width: 1060px;
    height: 32px;
    transition: height 0.3s ease; // 添加高度变化的过渡效果
    overflow: hidden; // 防止内容溢出
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .searchOperate {
    display: flex;
    align-items: center;
    .more {
      margin-left: 20px;
      display: flex;
      align-items: center;
    }
  }
}

/* 定义旋转动画 */
.rotate-180 {
  transition: transform 0.3s ease;
  transform: rotate(180deg);
}
</style>
